package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.CartProductDto;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:05
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {
    private static final String REDIS_CART_USERID_PREFIX = "cart_user_id_";

    @Autowired
    RedissonClient redissonClient;
    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        try {
            CreateOrderContext orderContext = (CreateOrderContext) context;
            // 获取购物车列表
            String userId = REDIS_CART_USERID_PREFIX + orderContext.getUserId();
            RMap<Long, CartProductDto> userCart = redissonClient.getMap(userId);
            // 根据订单商品清除购物车
            List<Long> buyProductIds = orderContext.getBuyProductIds();
            for (Long productId : buyProductIds) {
                if (userCart.containsKey(productId)) {
                    userCart.remove(productId);
                }
            }
        } catch (Exception e) {
            log.error("ClearCartItemHandler occur Exception :" + e);
            throw new BizException(OrderRetCode.REDIS_ERROR.getCode(),
                    OrderRetCode.REDIS_ERROR.getMessage());
        }
        return true;
    }
}
